<?php
namespace App\Http\Controllers\Admin;

use App\Models\AttachmentModel;
use App\Utils\UploadUtil;

class ImagesController extends BaseController
{

    protected $catalog; //存储目录
    protected $limit; //限制使用数量
    protected $field; //字段，用于展示位置以及保存
    protected $imgtype; //展示压缩图，还是原图

    function __construct()
    {
        $this->catalog = request()->input("catalog") ? : 'temp';
        $this->limit = request()->input("limit") ? : 1;
        $this->field = request()->input("field") ? : 'picture';
        $this->imgtype = request()->input("imgtype") ? : 1;
    }

    /**
     * 显示资源列表
     */
    public function index()
    {
        //基本参数
        $page = request()->input('page',1);
        $map[] = ['module_type',"=",1];

        $list = AttachmentModel::getPictureList(18,$page,$map);

        $arr = $list->toArray();

        return view('admin/public/images', [
            'total'=>$arr['total'],
            'list'=>$arr['data'],
            'links'=>$list,
            'model'=>[
                'catalog' => $this->catalog,
                'limit' => $this->limit,
                'field' => $this->field,
                'imgtype' => $this->imgtype,
                'page' => $page,
            ]
        ]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $res = UploadUtil::imagesUploads();
        return json_encode($res);
    }

    /**
     * 显示指定的资源
     */
    public function read()
    {
        try {
            $data = json_decode(request()->post("data"),true);
            if($data){
                foreach ($data as $k => $v) {
                    if($v[0] && $v[1]){
                        $arr['id'] = $v[0];
                        $arr['sort'] = $v[1];
                        $str[] = $arr;
                    }
                }
            }
            if($str){
                $list = arrSort($str,'sort');
                //根据点击序号进行排序
                //使用 order by field (id,2,3,1,4) ，影响不少性能
                $ids = implode(",", turnArr($list,'id'));
                $list_img = AttachmentModel::whereIn('id',explode(',',$ids))->orderByRaw("FIELD(id, " . $ids . ")")->select(['id','name','att_dir','satt_dir'])->get();
            }
            if($list_img){
                return $this->result(['list' => $list_img], 200, "使用图片成功");
            }
            return $this->result("", 500, "系统繁忙，请重试");
        } catch (\Exception $e) {
            return $this->result("", 500, $e->getMessage());
        }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        try {
            $ids = substr(request()->post("ids"), 1);
            $res = AttachmentModel::delPicture($ids);
            return $this->result("", $res['code'], $res['msg']);
        } catch (\Exception $e) {
            return $this->result("", 500, $e->getMessage());
        }
    }
}
